package com.example.demo.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @program: MyBatisGenerator
 * @author: daPangDong
 * @create: 2022-06-13 15:04
 */
@Service
public class AuthLoginIntercept implements HandlerInterceptor {

    private final static Log log = LogFactory.get();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //拦截所有的请求方法，是否需要登录
            HttpSession session = request.getSession();
            log.info("token:{}",session.getAttributeNames());

            //往session中存入你想要的东西
            session.setAttribute("token", "token");

            // 验证token信息
            this.validAuth(request);
        }
        return true;
    }


    /**
     * 验证token信息
     */
    private void validAuth(HttpServletRequest request) throws Exception {
        // 从 http 请求头中取出 token
        String token = request.getHeader("token");
//        if (StrUtil.isBlank(token)) {
//            throw new Exception("未获取到token, 请重新登录");
//        }
        // 验证 token
//        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
//        try {
//            jwtVerifier.verify(token);
//        } catch (Exception e) {
//            throw new CustomException("401", "token过期");
//        }
    }
}
